package edu.cicese.alz;

/**
 * Created by: Eduardo Quintana Contreras
 * Date: 11/06/12
 * Time: 04:31 PM
 */

import edu.cicese.alz.util.FileComparator;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public final class FileListing {

	static FilenameFilter jsonFilter = new FilenameFilter() {
		//TODO Filter surveys?
		public boolean accept(File dir, String name) {
			return name.toLowerCase().endsWith(".json");
		}
	};

	static FileFilter dirFilter = new FileFilter() {
		public boolean accept(File file) {
			return file.isDirectory();
		}
	};

	/**
	 * Demonstrate use.
	 *
	 * @param aArgs - <tt>aArgs[0]</tt> is the full name of an existing
	 *              directory that can be read.
	 */
	/*public static void main(String... aArgs) throws FileNotFoundException {
		File startingDirectory = new File("D:\\_proyectoAlz\\data\\users\\incense3");
		List<File> files = FileListing.getFileListing(startingDirectory);

		//print out all file names, in the the order of File.compareTo()
		for (File file : files) {
			System.out.println(file);
		}
	}*/

	/**
	 * Recursively walk a directory tree and return a List of all
	 * Files found; the List is sorted using FileComparator.
	 *
	 * @param dir is a valid directory, which can be read.
	 * @return a list of all the files (not directories) in descending order (by name)
	 */
	public static List<File> getFileListing(File dir) {
		List<File> result = getFileListingNoSort(dir);
		Collections.sort(result, new FileComparator());
		return result;
	}

	public static List<File> getFileListingNoSort(File dir) {
		List<File> result = new ArrayList<>();
		File[] files = dir.listFiles(jsonFilter);

		for (File file : files) {
			result.add(file);
		}
		
		files = dir.listFiles(dirFilter);
		for (File file : files) {
			List<File> deeperList = getFileListingNoSort(file);
			result.addAll(deeperList);
		}

		return result;
	}

	/**
	 * Directory is valid if it exists, does not represent a file, and can be read.
	 */
	/*static private void validateDirectory(File dir) {
		if (dir == null) {
			throw new IllegalArgumentException("Directory should not be null.");
		}
		if (!dir.exists()) {
			throw new FileNotFoundException("Directory does not exist: " + dir);
		}
		if (!dir.isDirectory()) {
			throw new IllegalArgumentException("Is not a directory: " + dir);
		}
		if (!dir.canRead()) {
			throw new IllegalArgumentException("Directory cannot be read: " + dir);
		}
	}*/


	/*static class FileComparator implements Comparator {

		public int compare(Object f1, Object f2) {
			return ((File) f1).getName().compareTo(((File) f2).getName());
		}
	}*/
}